package cn.mvc.web.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.fast.ioc.annotation.Repository;
import org.fast.jdbc.Converter;
import org.fast.jdbc.SqlHelper;
import org.fast.jdbc.support.DaoSupport;
import org.fast.web.Pager;

import cn.mvc.common.SqlMapping;

@Repository("webDao")
public class WebDao extends DaoSupport {

	/**
	 * 保存更新对象
	 * 
	 * @param sqlid
	 * @param obj
	 * @param field 对象字段属性
	 * @return
	 * @throws SQLException
	 */
	public int save(String sqlid, Object obj, String ...field) throws SQLException {
		String sql = SqlMapping.getSql(sqlid);
		Object[] params = Converter.parseFieldArray(obj, field);
		return update(sql, params);
	}

	/**
	 * 执行删除
	 * 
	 * @param sqlid
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	public int delete(String sqlid, String id) throws SQLException {
		String sql = SqlMapping.getSql(sqlid);
		return update(sql, id);
	}

	/**
	 * 获取对象
	 * 
	 * @param clazz
	 * @param sqlid
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public <T> T get(Class<T> clazz, String sqlid, Object... params)
			throws SQLException {
		String sql = SqlMapping.getSql(sqlid);
		return find(clazz, sql, params);
	}

	/**
	 * 统计记录
	 * 
	 * @param sqlid
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public int count(String sqlid, Object... params) throws SQLException {
		openConn();
		String sql = SqlMapping.getSql(sqlid);
		pstmt = SqlHelper.builParameter(conn, sql, params);
		rs = pstmt.executeQuery();
		int count = 0;
		if (rs.next()) {
			count = rs.getInt(1);
		}
		closeConn();
		return count;
	}

	/**
	 * 获取对象列表
	 * 
	 * @param clazz
	 * @param sqlid
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public <T> List<T> list(Class<T> clazz, String sqlid, Object... params)
			throws SQLException {
		List<T> list = new ArrayList<T>();
		String sql = SqlMapping.getSql(sqlid);
		list = query(clazz, sql, params);
		return list;
	}

	/**
	 * 分页查询 <br/>
	 * 
	 * @param clazz
	 * @param sqlid
	 * @param pager
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public <T> List<T> page(Class<T> clazz, String sqlid, Pager pager,
			Object... params) throws SQLException {
		String sql  = SqlMapping.getSql(sqlid);
		// mysql 分页 limt
		sql = sql + " limit " + pager.getStartRow() + "," + pager.getPageSize();
		List<T> list = query(clazz, sql, params);
		return list;
	}

}
